package utils.wallpaperCtrl;

import bean.GroupInfo;
import utils.command.CommandLinux;
import utils.fileHandler.FileHandler;
import utils.screenCtrl.ScreenCtrlLinux;
import utils.utilTime.UtilTime;
import utils.wallpaperHandler.WallpaperHandler;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WallpaperCtrlUKUILinux implements WallpaperCtrl {
    private static final WallpaperCtrlUKUILinux wallpaperCtrlUKUILinux;
    private static Process process;
    public static WallpaperPlay wallpaperPlay;
    private static String liveWallpaperSid = null;

    static {
        wallpaperCtrlUKUILinux = new WallpaperCtrlUKUILinux();
        wallpaperPlay = new WallpaperPlay();
    }

    @Override
    public void setPictureWallpaper(String path) {
        String[] args = new String[]{"/bin/bash", "-c", "gsettings set org.mate.background picture-filename " + "'" + path + "'"};
        String s = null;
        try {
            s = CommandLinux.oSCommandStatic(args);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(s);
        }
    }

    public static void setPictureWallpaperStatic(String path) {
        wallpaperCtrlUKUILinux.setPictureWallpaper(path);
    }

    @Override
    public void setLiveWallpaper(String path) throws IOException {
        /*File file = new File("/bin");
        Runtime runtime = Runtime.getRuntime();
        process = runtime.exec("/bin/bash", null, file);
        OutputStream outputStream = process.getOutputStream();
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream));
        printWriter.println("xwinwrap -ni -o 1 -fs -s -st -sp -b -nf -ov -d -- mpv -wid WID --fs --no-audio --loop \""+path+"\"\n");
        printWriter.flush();*/
        /*BufferedReader bufferedReaderInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line;
        while ((line = bufferedReaderInput.readLine())!=null) {
            System.out.println();
        }
        while ((line = bufferedReaderError.readLine())!=null) {
            System.out.println();
        }*/
        String[] args = new String[]{"/bin/bash", "-c", "xwinwrap -ni -o 1 -fs -s -st -sp -b -nf -ov -d -- mpv -wid WID --fs --no-audio --loop \"" + path + "\"\n"};
        String s = CommandLinux.oSCommandStatic(args);
        String regEx = ScreenCtrlLinux.getRegEx("pid of child process [a-zA-Z0-9]+", s);
        liveWallpaperSid = regEx.replace("pid of child process ", "");
    }

    public void setLiveWallpaper(String path,double transparency, double audio) throws IOException {
        String[] args;
        String transparencyStr = String.valueOf(transparency);
        if (transparencyStr.length()<4){
            transparencyStr=transparencyStr.substring(0,transparencyStr.length());
        }else {
            transparencyStr=transparencyStr.substring(0,4);
        }
        String audioStr=String.valueOf(audio);
        if (audioStr.length()<3){
            audioStr= audioStr.substring(0,audioStr.length());
        }else {
            audioStr.substring(0,3);
        }
        if (transparency==1.0){
            if (audio==1.0){
                args = new String[]{"/bin/bash", "-c", "xwinwrap -ni -o 1 -fs -s -st -sp -b -nf -ov -d -- mpv -wid WID --fs --loop \"" + path + "\"\n"};
            }else {
                args = new String[]{"/bin/bash", "-c", "xwinwrap -ni -o 1 -fs -s -st -sp -b -nf -ov -d -- mpv -wid WID --fs --no-audio --loop \"" + path + "\"\n"};
            }
        }else {
            if (audio==1.0){
                args = new String[]{"/bin/bash", "-c", "xwinwrap -ni -o "+transparencyStr+" -fs -s -st -sp -b -nf -d -- mpv -wid WID --fs --loop \"" + path + "\"\n"};
            }else {
                args = new String[]{"/bin/bash", "-c", "xwinwrap -ni -o "+transparencyStr+" -fs -s -st -sp -b -nf -d -- mpv -wid WID --fs --no-audio --loop \"" + path + "\"\n"};
            }
        }
        String s = CommandLinux.oSCommandStatic(args);
        String regEx = ScreenCtrlLinux.getRegEx("pid of child process [a-zA-Z0-9]+", s);
        liveWallpaperSid = regEx.replace("pid of child process ", "");
    }

    public static void setLiveWallpaperStatic(String path) throws IOException {
        wallpaperCtrlUKUILinux.setLiveWallpaper(path);
    }

    public static void setLiveWallpaperStatic(String path, double transparency, double audio) throws IOException {
        wallpaperCtrlUKUILinux.setLiveWallpaper(path,transparency,audio);
    }

    @Override
    public void exitLiveWallpaper() {
        if (liveWallpaperSid == null) {
            System.out.println("Log : LiveWallpaper has already exit before " + UtilTime.getStringTime(UtilTime.getUnixTimeLNow()));
        } else {
            String[] args = new String[]{"/bin/bash", "-c", "kill " + liveWallpaperSid};
            try {
                CommandLinux.oSCommandStatic(args);
                CommandLinux.oSCommandStatic(args);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Log : LiveWallpaper exit at " + UtilTime.getStringTime(UtilTime.getUnixTimeLNow()));
            liveWallpaperSid = null;
        }
    }

    public static void exitLiveWallpaperStatic() {
        wallpaperCtrlUKUILinux.exitLiveWallpaper();
    }

    public static class GroupTimerTask extends TimerTask{
        double transparency;
        double audio;
        @Override
        public void run() {
            wallpaperPlay.playNext(transparency,audio);
        }
        GroupTimerTask(double transparency, double audio){
            this.transparency=transparency;
            this.audio=audio;
        }
    }

    public static void setWallpaperPlayGroup(GroupInfo groupInfo) {
        setWallpaperPlayGroup(FileHandler.getIntervalTime(),FileHandler.getTransparency(), FileHandler.getAudio(),groupInfo);
    }

    public static void setWallpaperPlayGroup(long intervalTime, double transparency, double audio, GroupInfo groupInfo) {
        wallpaperPlay.setGroupInfo(groupInfo);
        Timer timer = new Timer();
        timer.schedule(new GroupTimerTask(transparency, audio),intervalTime);
    }

    public static class WallpaperPlay {
        public GroupInfo groupInfo;
        public List<String> imagePaths;
        int start = 1, end;

        public void playNext(double transparency, double audio) {
            if (start > end) {
                start = start % end;
            }
            String s = imagePaths.get(start-1);
            if (s.contains(FileHandler.getImageWallpaperPath())){
                exitLiveWallpaperStatic();
                setPictureWallpaperStatic(WallpaperHandler.gethDImagePath(s.replace("file:","")));
            }else if (s.contains(FileHandler.getVideoWallpaperPath())){
                exitLiveWallpaperStatic();
                try {
                    setLiveWallpaperStatic(WallpaperHandler.gethDVideoPath(s.replace("file:","")),transparency,audio);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            start++;
        }

        public void setGroupInfo(GroupInfo groupInfo) {
            this.groupInfo = groupInfo;
            end = groupInfo.getNumber();
            imagePaths = groupInfo.getImagePath();
        }
    }
}
